package com.sb.ble.codetest;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.Toast;

import com.orm.SugarRecord;
import com.sb.ble.codetest.commons.DateUtil;
import com.sb.ble.codetest.commons.PDALogUtils;
import com.sb.ble.codetest.commons.RandomUntil;
import com.sb.ble.codetest.commons.Util;
import com.sb.ble.codetest.commons.UtilsLog;
import com.sb.ble.codetest.model.GoodsModel;
import com.sb.ble.codetest.model.TypeModel;
import com.sb.ble.codetest.model.VideoUploadModel;
import com.vincent.videocompressor.VideoCompress;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements ApiHttp, EasyPermissions.PermissionCallbacks {


    @BindView(R.id.button1)
    Button button1;
    @BindView(R.id.button2)
    Button button2;
    @BindView(R.id.button3)
    Button button3;
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    private long startTime, endTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        if (EasyPermissions.hasPermissions(this, PERMISSIONS)) {//检查是否获取该权限
            UtilsLog.e("zzl=已获取权限");
        } else {
            UtilsLog.e("zzl=meiyou===权限");
            EasyPermissions.requestPermissions(this, "必要的权限", 0, PERMISSIONS);
        }
//        test01();
//        MyTestutils.getIMEI(this);
//        MyTestutils.JudgeSIM(this);
//        String str0 = "", str1 = "";
//        str0 = CommonUtils.getIMEI(this, 0);
//        str1 = CommonUtils.getIMEI(this, 1);
//        UtilsLog.e("手机IMEI---1---" + str0);
//        UtilsLog.e("手机IMEI---2---" + str1);


        Video_start_time = DateUtil.currentTime2();
    }

    void test01() {
        List<TypeModel> typeModelList = new ArrayList<>();
        TypeModel model = null;
        for (int i = 0; i < 10; i++) {
            model = new TypeModel();
            if (i == 1 || i == 2 || i == 3) {
                model.setCode("bbb");
                model.setName("ccccc");
                model.setColor(1);
            } else {
                model.setCode("A00=" + i);
                if (i % 2 == 0) {
                    model.setName("轮胎规格型号" + i);
                } else {
                    model.setName("hello" + i);
                }
                model.setColor(i);
            }
            typeModelList.add(model);
        }
        UtilsLog.e("typeModelList===size===" + typeModelList.size());
        UtilsLog.e("typeModelList===" + typeModelList.toString());

        typeModelList = typeModelList.stream().distinct().collect(Collectors.toList());
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        UtilsLog.e("===========");
        UtilsLog.e("typeModelList===size===" + typeModelList.size());
        UtilsLog.e("typeModelList==distinct===" + typeModelList.toString());

//        List<TypeModel> typeModelList_filter = typeModelList.stream().
//                filter(p -> p.getName().contains("轮胎")).collect(Collectors.toList());
//        UtilsLog.e("typeModelList===filter====" + typeModelList_filter.toString());
//
//
//        typeModelList.removeIf(p -> p.getName().contains("轮胎"));
//        UtilsLog.e("typeModelList===removeIf===" + typeModelList.toString());
//        typeModelList.removeIf(p->!p.getName().contains("轮胎"));
//        UtilsLog.e("typeModelList===removeIf=!!!!!==" + typeModelList.toString());
    }

    void sugardb_test_insert() {
        List<GoodsModel> goodsModelList = new ArrayList<>();
        GoodsModel model = null;
        for (int i = 0; i < 10; i++) {
            model = new GoodsModel();
            model.setGoodid("good" + i);
            model.setGoodname("good_name" + i);
            model.setGoodtitle(RandomUntil.getNumSmallLetter(5));
            goodsModelList.add(model);
        }
        SugarRecord.saveInTx(goodsModelList);
    }

    void sugardb_test_query() {
        List<GoodsModel> list = GoodsModel.listAll(GoodsModel.class);
        if (list != null && list.size() > 0) {
            UtilsLog.e("111===" + list.toString());
        }
    }

    void sugardb_test_query(String sql, String value) {
        List<GoodsModel> list = GoodsModel.find(GoodsModel.class, sql, value);
        if (list != null && list.size() > 0) {
            UtilsLog.e("2222===" + list.toString());
        }
    }

    @OnClick({R.id.button1, R.id.button2, R.id.button3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button1:
                Video_start_time = DateUtil.currentTime2();
                startVideo();
//                saveVideo();
//                sugardb_test_insert();
//                if  (!ButtonUtils.isFastDoubleClick(R.id.button1)) {
//                    //写你相关操作即可
//                    UtilsLog.e("不是重复点击========="  );
//                }else {
//                    UtilsLog.e("===============是重复点击========="  );
//                }
                break;
            case R.id.button2:
//                sugardb_test_query();

                startCamera();
                break;
            case R.id.button3:
                sugardb_test_query("goodname = ?", "good_name5");
                break;
        }
    }

    @Override
    public void test_0() {

    }

    @Override
    public void test_1(String str) {

    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    /**
     * 内容提供者和XML配置一样
     */
    String fileProvider = "com.sb.ble.codetest.fileprovider";

    String filePath = "", realVideoPath = "";

    void saveVideo() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            String logStr = "\n" + "外检上传视频--校验存储空间--成功---" + "\n";
            PDALogUtils.createLogFile(0, logStr.getBytes());

            String timeStamp = String.valueOf(System.currentTimeMillis());
//          filePath = Environment.getExternalStorageDirectory().getPath() + "/myvideo/" + timeStamp+".mp4";
//            filePath =  Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/myvideo/";
            filePath = Environment.getExternalStorageDirectory() + "/myvideo/";
            UtilsLog.e("saveVideo--视频路径=filePath==" + filePath);
//            filePath = Environment.getExternalStorageDirectory() + "/myvideo/";
            File mediaStorageDir = new File(filePath);
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    UtilsLog.e("saveVideo--视频路径--文件夹创建失败");
                    String logStr22 = "\n" + "saveVideo--视频路径--文件夹创建失败---" + "\n" + filePath + "\n";
                    PDALogUtils.createLogFile(0, logStr22.getBytes());
                    return;
                }
            }
            String videoPath = filePath + timeStamp + ".mp4";
            realVideoPath = videoPath;
            UtilsLog.e("saveVideo--视频路径=videoPath==" + videoPath);
            String logStr22 = "\n" + "saveVideo--视频路径--成功---" + "\n" + videoPath + "\n";
            PDALogUtils.createLogFile(0, logStr22.getBytes());
//                String filePath = FileManager.get().getRootFile() + "/msc/"  + "111111.mp4";   // 保存路径
//            android.net.Uri uri = Uri.fromFile(new File(videoPath));   // 将路径转换为Uri对象
//            Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);  // 表示跳转至相机的录视频界面
//            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0.8);    // MediaStore.EXTRA_VIDEO_QUALITY 表示录制视频的质量，从 0-1，越大表示质量越好，同时视频也越大
////            MediaStore.EXTRA_SCREEN_ORIENTATION
//            //大小限制是long型，int 型无效，所以后边要写一个L
////            intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 60 * 10 * 1024 * 1024L);//限制录制大小(10M=10 * 1024 * 1024L)
////            intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,90);
////            intent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,180);
//            intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, 0);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);    // 表示录制完后保存的录制，如果不写，则会保存到默认的路径，在onActivityResult()的回调，通过intent.getData中返回保存的路径
//            intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 60 * 10);   // 设置视频录制的最长时间
//            startActivityForResult(intent, 666);  // 跳转


            MimeTypeMap mime = MimeTypeMap.getSingleton();
            File newFile = new File(videoPath);
            String ext = newFile.getName().substring(newFile.getName().lastIndexOf(".") + 1);
            String type = mime.getMimeTypeFromExtension(ext);
            try {
                Intent intent = new Intent();
                intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, 0);
                intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 60 * 10);   // 设置视频录制的最长时间
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(this, "com.sb.ble.codetest.fileProvider", newFile);
                    intent.setDataAndType(contentUri, type);
                } else {
                    intent.setDataAndType(Uri.fromFile(newFile), type);
                }
                startActivityForResult(intent, 666);
            } catch (ActivityNotFoundException anfe) {
                Toast.makeText(this, "No activity found to open this attachment.", Toast.LENGTH_LONG).show();
            }


        } else {
            String logStr = "\n" + "saveVideo--外检上传视频--校验存储空间--失败" + "\n";
            PDALogUtils.createLogFile(0, logStr.getBytes());
        }
    }

    boolean UpVideo_ok = false;
    Uri Uri;
    private String Video_start_time = "", Video_End_time = "";//录像开始时间，结束时间

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UtilsLog.e("requestCode==" + requestCode);
        if (data != null) {
            if (requestCode == 666) {
                Video_End_time = DateUtil.currentTime2();
                Uri = data.getData();
//                UtilsLog.e("Uri.toString()==" + Uri.toString());
                UtilsLog.e("Uri.mVideoFile==" + mVideoPath);
                String logStr22 = "\n" + "视频路径---data---Uri.getPath()---" + "\n" + Uri.getPath() + "\n"
                        + "mVideoFile:::::" + mVideoPath + "\n";
                PDALogUtils.createLogFile(0, logStr22.getBytes());
                 UtilsLog.e("拍摄结束。");

                runnable = new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = 1;
//                        message.obj = Uri.getPath();
                        message.obj = mVideoPath;
                        handlerUI.sendMessage(message);
//                            handler_zhaungsuji.postDelayed(runnable_zhuangsuji, 1 * 1000);
                    }
                };
                handlerUI.post(runnable);
//                getDataUploadVideo(new File(Uri.getPath()));
            }
        }
    }

    //运行在主线程的Handler：使用Android默认的UI线程中的Looper
    public Handler handlerUI = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    compressVideo(mVideoPath);
                    break;
            }
        }
    };

    private Runnable runnable;
    String videoPath = "";

    String compressVideo(String videoUriString) {
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String compressFilePath = "";
//          filePath = Environment.getExternalStorageDirectory().getPath() + "/myvideo/" + timeStamp+".mp4";

//        String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)+ "/compress/";
        String filePath = Environment.getExternalStorageDirectory() + "/compress/";
//        String filePath = Environment.getExternalStorageDirectory() + "/myvideo/compress/";
//        String filePath = Environment.getExternalStorageDirectory() + "/myvideo";
        File mediaStorageDir = new File(filePath);
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                UtilsLog.e("compressVideo--视频路径-compress-文件夹创建失败");
                String logStr22 = "\n" + "compressVideo--视频路径--文件夹创建失败-compress--" + "\n" + filePath + "\n";
                PDALogUtils.createLogFile(0, logStr22.getBytes());
            }
        }
        videoPath = filePath + timeStamp + ".mp4";
        UtilsLog.e("compressVideo--视频路径=videoPath=compress=" + videoPath);
        String logStr22 = "\n" + "compressVideo--视频路径=videoPath=compress=" + "\n" + videoPath + "\n";
        PDALogUtils.createLogFile(0, logStr22.getBytes());
        model = new VideoUploadModel();
        model.setSize(videoUriString);//原视频路径
        model.setZp(videoPath);//压缩后的保存路径
        model.setStatement("0");
        model.save();
        String logStr22az = "\n" + "compressVideo--VideoUploadModel--" + "\n" + model.toString() + "\n";
        PDALogUtils.createLogFile(0, logStr22az.getBytes());

        new Thread() {

            @Override
            public void run() {
                handler.post(myRunnable);//调用Handler.post方法；
            }
        }.start();
        return compressFilePath;
    }

    private Handler handler = new Handler();
    MyRunnable myRunnable = new MyRunnable();//定义MyRunnable的对象；
    VideoUploadModel model = null;

    class MyRunnable implements Runnable {//内部类实现Runnable接口；

        @Override
        public void run() {//还是在Runnable重写的run()方法中更新界面；
//            text.setText("使用Handler更新了界面");
//            videoCompress(model.getSize(), model.getZp(), model);
//            video_VideoProcessor(model.getSize(), model.getZp(), model);
            videoCompress_low(model.getSize(), model.getZp(), model);
        }
    }

    void videoCompress_low(String videoUriString, String videoPath, final VideoUploadModel model) {
//        String destPath = tv_output.getText().toString() + File.separator + "VID_" + new SimpleDateFormat("yyyyMMdd_HHmmss", getLocale()).format(new Date()) + ".mp4";
        VideoCompress.compressVideoLow(videoUriString, videoPath, new VideoCompress.CompressListener() {
            @Override
            public void onStart() {
                String str = "Compressing..." + "\n"
                        + "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date())
                        + "\n" + model.toString();
                UtilsLog.e("onStart==" + str);
                PDALogUtils.createLogFile(0, str.getBytes());
                startTime = System.currentTimeMillis();
                Util.writeFile(MainActivity.this, "Start at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
            }

            @Override
            public void onSuccess() {
                String str = "\n"
                        + "Compress Success!" + "\n"
                        + "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n" + model.toString();
                UtilsLog.e("onSuccess==" + str);
                PDALogUtils.createLogFile(0, str.getBytes());
                endTime = System.currentTimeMillis();
                Util.writeFile(MainActivity.this, "End at: " + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()) + "\n");
                Util.writeFile(MainActivity.this, "Total: " + ((endTime - startTime) / 1000) + "s" + "\n");
                Util.writeFile(MainActivity.this);
//                getDataUploadVideo(model, true, "");
            }

            @Override
            public void onFail() {
                UtilsLog.e("onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
                String str = "onFail==Compress Failed!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date());
                endTime = System.currentTimeMillis();
                PDALogUtils.createLogFile(0, str.getBytes());
                Util.writeFile(MainActivity.this, "Failed Compress!!!" + new SimpleDateFormat("HH:mm:ss", getLocale()).format(new Date()));
            }

            @Override
            public void onProgress(float percent) {
                String str = "视频压缩进度==" + String.valueOf(percent) + "%" + "\n" + model.toString() + "\n";
                PDALogUtils.createLogFile(0, str.getBytes());
                UtilsLog.e("onProgress====" + str);
                model.setProgress(percent);
//                EventBus.getDefault().post(model);
            }
        });
    }

    private Locale getLocale() {
        Configuration config = getResources().getConfiguration();
        Locale sysLocale = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            sysLocale = getSystemLocale(config);
        } else {
            sysLocale = getSystemLocaleLegacy(config);
        }

        return sysLocale;
    }

    @SuppressWarnings("deprecation")
    public static Locale getSystemLocaleLegacy(Configuration config) {
        return config.locale;
    }

    @TargetApi(Build.VERSION_CODES.N)
    public static Locale getSystemLocale(Configuration config) {
        return config.getLocales().get(0);
    }

    /**
     * 启动相机，创建文件，并要求返回uri
     */
    private Uri mVideoUri;
    private Uri mImageUri;
      File mVideoFile;
      String mVideoPath;
    private String mVideoName;
    private String mImageName;
    private String mImagePath;
    private File mImageFile;
    private void startVideo() {
        Intent intent = new Intent();
        //指定动作，启动相机
        intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
         UtilsLog.e("指定启动相机动作，完成。");
        //创建文件
        createVideoFile();
         UtilsLog.e("创建视频文件结束。");
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
         UtilsLog.e("添加权限。");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //做一些处理
            //获取uri
            mVideoUri = FileProvider.getUriForFile(this, fileProvider, mVideoFile);
        } else {
            //在版本低于此的时候，做一些处理
            mVideoUri = Uri.fromFile(mVideoFile);
        }

         UtilsLog.e("根据视频文件路径获取uri。");
        //将uri加入到额外数据
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mVideoUri);
         UtilsLog.e("将uri加入启动相机的额外数据。");
         UtilsLog.e("启动相机...");
        //启动相机并要求返回结果
        startActivityForResult(intent, 666);
         UtilsLog.e("拍摄中...");
    }

    /**
     * 创建视频文件
     */
    private void createVideoFile() {
         UtilsLog.e("开始创建图片文件...");
        //设置图片文件名（含后缀），以当前时间的毫秒值为名称
        mVideoName = Calendar.getInstance().getTimeInMillis() + ".mp4";
         UtilsLog.e("设置图片文件的名称为：" + mVideoName);
        //创建图片文件
        mVideoFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/myvideo/", mVideoName);
        //将图片的绝对路径设置给mImagePath，后面会用到
        mVideoPath = mVideoFile.getAbsolutePath();
        //按设置好的目录层级创建
        mVideoFile.getParentFile().mkdirs();
         UtilsLog.e("按设置的目录层级创建图片文件，路径：" + mVideoPath);
        //不加这句会报Read-only警告。且无法写入SD
        mVideoFile.setWritable(true);
         UtilsLog.e("将图片文件设置可写。");
    }





    /**
     * 启动相机，创建文件，并要求返回uri
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void startCamera() {
        Intent intent = new Intent();
        //指定动作，启动相机
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        UtilsLog.e( "指定启动相机动作，完成。");
        //创建文件
        createImageFile();
        UtilsLog.e( "创建图片文件结束。");
        //添加权限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        UtilsLog.e( "添加权限。");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //做一些处理
            //获取uri
            mImageUri = FileProvider.getUriForFile(this, fileProvider, mImageFile);
        } else {
            //在版本低于此的时候，做一些处理
            mImageUri = Uri.fromFile(mImageFile);
        }

        UtilsLog.e( "根据图片文件路径获取uri。");
        //将uri加入到额外数据
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
        UtilsLog.e( "将uri加入启动相机的额外数据。");
        UtilsLog.e( "启动相机...");
        //启动相机并要求返回结果
        startActivityForResult(intent, 666);
        UtilsLog.e( "拍摄中...");
    }


    /**
     * 创建图片文件
     */
    private void createImageFile() {
        UtilsLog.e( "开始创建图片文件...");
        //设置图片文件名（含后缀），以当前时间的毫秒值为名称
        mImageName = Calendar.getInstance().getTimeInMillis() + ".jpg";
        UtilsLog.e( "设置图片文件的名称为：" + mImageName);
        //创建图片文件
        mImageFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/temp_my_app/", mImageName);
        //将图片的绝对路径设置给mImagePath，后面会用到
        mImagePath = mImageFile.getAbsolutePath();
        //按设置好的目录层级创建
        mImageFile.getParentFile().mkdirs();
        UtilsLog.e( "按设置的目录层级创建图片文件，路径：" + mImagePath);
        //不加这句会报Read-only警告。且无法写入SD
        mImageFile.setWritable(true);
        UtilsLog.e( "将图片文件设置可写。");
    }
}
